﻿using NUnit.Framework;
using Reticulum.Properties;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using Reticulum.User;
using System.Runtime.InteropServices;
using Reticulum.工具类;
using System.Diagnostics;
using Reticulum.Communication;
using Reticulum.MyBackgroundImg;
using System.Net.Sockets;
using System.Threading;

namespace Reticulum
{
    public partial class Client : Form
    {
        public Client()
        {
            InitializeComponent();
            //changeSize();
            //改变大小的方法
            //通过导入
        }

        //private void changeSize()
        //{
        //    throw new NotImplementedException();
        //}

        //获取此电脑的分辨率
        public static int ThisW = Screen.PrimaryScreen.Bounds.Width;
        public static int ThisH = Screen.PrimaryScreen.Bounds.Height;


        private void Client_MouseDown(object sender, MouseEventArgs e)
        {

        }


        //无边框拖动窗体-----------------------------------------------
        private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
        {
            DialogResult sb;
            sb = MessageBox.Show("确定要退出吗？", "", MessageBoxButtons.YesNo);
            if (sb == DialogResult.Yes)
            {
                TiamIsOver.Start();
            }
            else { }
        }

        private void mini_MouseDown(object sender, MouseEventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
        }

        //------------------------------------------------------------    一个按钮按顺序触发两个事件
        public static bool bOpen = true;
        private void max_Click(object sender, EventArgs e)
        {
            DBHelps.Command("delete FlieTeamLog");
            {
                if (bOpen)
                {
                    //Client client = new Client();
                    //this.MaximumSize.Height = ThisH;
                    //client.MaximumSize.Width = ThisW;
                    //this.Size.Height = ThisH;

                    //this.WindowState = FormWindowState.Maximized;//最大化窗体大小
                    max.BackgroundImage = Resources.扩大2;//改变按钮图片
                }
                else
                {
                    //this.WindowState = FormWindowState.Normal;//默认窗体大小
                    max.BackgroundImage = Resources.扩大;//改变按钮图片
                }
                bOpen = !bOpen;
            }//切换最大化和标准化的方法
        }

        public void Client_Load(object sender, EventArgs e)
        {
            CurrentlyDownload_Click(sender, e);//

            //显示主菜单和下拉菜单的用户昵称

            //用户姓名在容器中居中
            base.OnResize(e);
            int x = (int)(0.5 * (LinkState.Width - FriendsState.Width));
            int y = FriendsState.Location.Y;
            FriendsState.Location = new System.Drawing.Point(x, y);

            //Button button = new Button();
            //panel3.ControlAdded(button);


            //设置子窗体在容器里的方法
            LoginHome.masterForm.Dock = DockStyle.Fill;
            LoginHome.masterForm.TopLevel = false;
            ServiceSide.Controls.Clear();//清除容器
            LoginHome.masterForm.Parent = this.ServiceSide;
            ServiceSide.Controls.Add(LoginHome.masterForm);
            LoginHome.masterForm.Show();
            FriendsList.Controls.Clear();

            //添加该用户好友
            var DML = string.Format("select * from MyFriends mf,Users u where mf.MyfriendID = u.UserID and mf.UserID = {0}", ThisMyInfo.UserID);
            SqlDataReader reader = DBHelps.Select(DML);
            int i = 0;
            while (reader.Read())
            {
                friend = new Button();
                this.Controls.Add(friend);
                FriendsList.Controls.Add(friend);
                friend.Dock = DockStyle.Top;
                friend.Width = 228;
                friend.Height = 40;
                friend.FlatStyle = FlatStyle.Flat;
                friend.FlatAppearance.BorderSize = 0;
                friend.Text = reader["UserName"].ToString();
                friend.BackColor = Color.Transparent;
                friend.FlatStyle = FlatStyle.Flat;

                button[i] = friend.Text;
                i++;
                friend.Click += Friend_Click;
            }
            reader.Close();
            DBHelps.reader = null;
            //----

            TIME.Start();

            //显示主菜单和下拉菜单的用户昵称
            label2.Text = ThisMyInfo.UserName;

            //居中显示





            //调用 button3 的单击事件 加载用户的所有文件
            button3_Click(sender, e);

            //显示头像
            this.UserImges.BackgroundImage = ImageShow.IamgeShows();
        }

        private void UserName_Click(object sender, EventArgs e)
        {

        }

        private void panel1_Paint(object sender, PaintEventArgs e)
        {

        }
        private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
        {

        }

        private void button5_Paint(object sender, PaintEventArgs e)  //圆形按钮--用户的头像设置
        {
            Button btn = sender as Button;
            System.Drawing.Drawing2D.GraphicsPath btnPath = new System.Drawing.Drawing2D.GraphicsPath();
            System.Drawing.Rectangle newRectangle = btn.ClientRectangle;
            newRectangle.Inflate(-2, -1);
            e.Graphics.DrawEllipse(System.Drawing.Pens.BlanchedAlmond, newRectangle);
            newRectangle.Inflate(-2, -4);
            btnPath.AddEllipse(newRectangle);
            btn.Region = new System.Drawing.Region(btnPath);
        }

        private void UserImges_Click_1(object sender, EventArgs e)
        {
            PerfectInformation PIuser = new PerfectInformation();//实例化窗体
            PIuser.ShowDialog();//加载模式窗体
        }

        private void label2_Click(object sender, EventArgs e)//返回登陆界面
        {
            
        }

        public static string saveName;//文件名称
        public static int FlieLLength;//文件大小
        public static string strPicPath;//图片存放路径（全路径）
        public static string extension;//文件后缀名（带点）
        public static string original_file_name;//原文件名
        public static string upload_file_name;//上传后文件名
        public static int Path_Length;//保存路径长度
        public static string fileNames = null;// 数据库获取的上传文件名
        public static string extension_1;//文件保存时 获取选择listview项的文件后缀名
        public static int CmmandShuxing = 0;//切换文件属性和重命名窗体的判断条件


        private void UpLoadFlie_Click(object sender, EventArgs e)
        {
            Upload.StartUpLoad();
            Client_Load(sender, e);//调用Load加载事件，实现重新加载数据
            //button3_Click(sender, e);
        }
        public static bool User = true;
        public static bool User1 = true;
        private void button1_Click(object sender, EventArgs e)
        {
            
            if (User)
            {
                button2.Visible = true;
            }
            else
            {
                button2.Visible = false;
                button3.Visible = false;
                button4.Visible = false;
                button5.Visible = false;
            }
            User = !User;
        }

        private void button2_Click_1(object sender, EventArgs e)
        {
            if (User1 == true)
            {
                button5.Visible = true;
                button4.Visible = true;
                button3.Visible = true;
            }
            else
            {
                button3.Visible = false;
                button5.Visible = false;
                button4.Visible = false;
            }
            User1 = !User1;
        }

        private void Navigationbar_MouseMove(object sender, MouseEventArgs e)
        {
        }

        //无边框拖动窗体-----------------------------------------------
        [DllImport("user32.dll")]//*********************拖动无窗体的控件  需要引用
        public static extern bool ReleaseCapture();
        [DllImport("user32.dll")]
        public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
        public const int W = 0x0112;
        public const int S = 0xF010;
        public const int H = 0x0002;

        private void Navigationbar_MouseDown(object sender, MouseEventArgs e)
        {
            ReleaseCapture();
            SendMessage(this.Handle, W, S + H, 0);//*********************调用移动无窗体控件函数
        }

        
        private void DownLoad_Click(object sender, EventArgs e)
        {
            Download.StartDownLoad();
        }
        private void Delete_Click(object sender, EventArgs e)//删除
        {
            try
            {
                //右键菜单的删除功能
                DialogResult result = MessageBox.Show("确定要删除文件吗？", "", MessageBoxButtons.YesNo);
                if (result == DialogResult.Yes)
                {
                    if (this.listView1.SelectedItems.Count > 0)
                    {
                        string a = listView1.SelectedItems[0].Text;//获取删除的文件名

                        string sql = string.Format("update FlieInfo set Belongs='回收站' where UserID={0} and FlieName+FlieSuffix='{1}'", ThisMyInfo.UserID,a);

                        bool result1 = DBHelps.Command(sql);
                        if (result1)
                        {
                            MessageBox.Show("删除成功！\n已经放入回收站了。");
                            button3_Click(sender,e);
                        }
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show("删除失败");
            }
        }


        private void Refreshs_Click(object sender, EventArgs e)
        {
            //循环判断 删除现有项
            Client_Load(sender, e);//调用Load加载事件，实现重新加载数据
        }
        public void button3_Click(object sender, EventArgs e)//全部文件
        {
            PrivacyLogin.Visible = false;//隐藏隐私控件登陆容器
            PrivacyPwd.Visible = false;//隐藏隐私控件注册容器
            listView1.ContextMenuStrip = RightClick;//重新设置右键出来的方式 
            //使用listView 显示该用户的文件-------------
            this.listView1.Items.Clear();//清楚所有项,避免重复！

            string sql = string.Format("select (f.FlieName + f.FlieSuffix) 文件名,f.FlieGetTime 上传日期,cast((FlieLength/1024/1024)as decimal(20,3)) 文件大小,f.FlieSuffix 文件类型 " +
                "from FlieInfo f,Users u where f.UserID = u.UserID and u.UserID = '{0}' and f.Belongs = '首页' order by 文件类型", ThisMyInfo.UserID);

            SqlDataReader reader = DBHelps.Select(sql);
            while (reader.Read())
            {
                //创建ListViewItem对象，并设置Text属性
                ListViewItem item1 = new ListViewItem(reader["文件名"].ToString());

                //向ListViewItem对象中依次添加子项
                item1.SubItems.Add(reader["上传日期"].ToString());
                item1.SubItems.Add(reader["文件大小"].ToString());

                //向ListView控件中添加项
                this.listView1.Items.Add(item1);

                //设置该文件图标
                string Suffix = (reader["文件类型"].ToString());
                item1.ImageIndex = IfSuffix.IfSuffixs(Suffix);

                //item1.SubItems.

            }
            reader.Close();
            DBHelps.reader = null;
        }


        private void button4_Click_1(object sender, EventArgs e)//相册
        {
            PrivacyLogin.Visible = false;//隐藏隐私控件登陆容器
            PrivacyPwd.Visible = false;//隐藏隐私控件注册容器
            listView1.ContextMenuStrip = RightClick;//重新设置右键出来的方式
            //使用listView 显示该用户的文件-------------
            this.listView1.Items.Clear();//清除所有项,避免重复！

            string sql = string.Format("select (f.FlieName + f.FlieSuffix) 文件名,f.FlieGetTime 上传日期,cast((FlieLength/1024/1024)" +
                "as decimal(20,3)) 文件大小,f.FlieSuffix 文件类型 from FlieInfo f,Users u where " +
                "f.UserID = u.UserID and f.FlieSuffix in( '.jpg','.jpeg','.gif','.png','.bmp') and u.UserID= '{0}' and f.Belongs = '首页'", ThisMyInfo.UserID);

            while (DBHelps.Select(sql).Read())
            {
                //创建ListViewItem对象，并设置Text属性
                ListViewItem item1 = new ListViewItem(DBHelps.Select(sql)["文件名"].ToString());

                //向ListViewItem对象中依次添加子项
                item1.SubItems.Add(DBHelps.Select(sql)["上传日期"].ToString());
                item1.SubItems.Add(DBHelps.Select(sql)["文件大小"].ToString());

                //向ListView控件中添加项
                this.listView1.Items.Add(item1);

                //设置该文件图标
                string Suffix = (DBHelps.Select(sql)["文件类型"].ToString());
                item1.ImageIndex = IfSuffix.IfSuffixs(Suffix);

                //item1.SubItems.

            }
            DBHelps.Select(sql).Close();
            DBHelps.reader = null;
        }


        private void button5_Click(object sender, EventArgs e)//音乐
        {
            PrivacyLogin.Visible = false;//隐藏隐私控件登陆容器
            PrivacyPwd.Visible = false;//隐藏隐私控件注册容器
            listView1.ContextMenuStrip = RightClick;//重新设置右键出来的方式
            //使用listView 显示该用户的文件-------------
            this.listView1.Items.Clear();//清楚所有项,避免重复！

            string sql = string.Format("select u.UserID,(f.FlieName + f.FlieSuffix) 文件名,f.FlieGetTime 上传日期, cast((FlieLength / 1024 / 1024)" +
                " as decimal(20, 3)) 文件大小,f.FlieSuffix 文件类型 from FlieInfo f,Users u  where f.UserID = u.UserID and  f.FlieSuffix " +
                "in( '.mp3','.wqv','.wma','.flac','.ape')	and u.UserID ='{0}' and f.Belongs = '首页'", ThisMyInfo.UserID);

            while (DBHelps.Select(sql).Read())
            {
                //创建ListViewItem对象，并设置Text属性
                ListViewItem item1 = new ListViewItem(DBHelps.Select(sql)["文件名"].ToString());

                //向ListViewItem对象中依次添加子项
                item1.SubItems.Add(DBHelps.Select(sql)["上传日期"].ToString());
                item1.SubItems.Add(DBHelps.Select(sql)["文件大小"].ToString());

                //向ListView控件中添加项
                this.listView1.Items.Add(item1);

                //设置该文件图标
                string Suffix = (DBHelps.Select(sql)["文件类型"].ToString());
                item1.ImageIndex = IfSuffix.IfSuffixs(Suffix);

                //item1.SubItems.

            }
            DBHelps.Select(sql).Close();
            DBHelps.reader = null;
        }

        private void 上传ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            UpLoadFlie_Click(sender, e);
        }

        public bool or = true;//视图切换的变量
        private void button6_Click(object sender, EventArgs e)
        {
            if (or)
            {
                button6.BackgroundImage = Resources.图片视图;
                listView1.View = View.Details;
            }
            else
            {
                button6.BackgroundImage = Resources.列显示视图;
                listView1.View = View.LargeIcon;
            }
            or = !or;
        }

        bool ShowMyMenu = false;
        bool ShowMyMenu2 = false;

        public static string choice_term = null;
        private void listView1_MouseClick(object sender, MouseEventArgs e)
        {
            /*
             * 右键选择到项时才出现的右键菜单
             */
            if (e.Button == MouseButtons.Right)
            {
                this.RightClick.Show(this.listView1, e.X, e.Y);
            }
            choice_term = listView1.SelectedItems[0].Text;

            if (e.Button == MouseButtons.Right)
            {
                this.contextMenuStrip1.Show(this.listView1, e.X, e.Y);
            }
            choice_term = listView1.SelectedItems[0].Text;
        }

        private void panel3_Paint(object sender, PaintEventArgs e)
        {

        }

        private void Navigationbar_Paint(object sender, PaintEventArgs e)
        {

        }

        public static UserFrom userFrom = null;
        private void button7_Click(object sender, EventArgs e)
        {
            this.Hide();

            userFrom = new UserFrom();
            userFrom.ShowDialog();

            this.Close();
        }

        private void Client_FormClosing(object sender, FormClosingEventArgs e)
        {
            var DML = string.Format("update Users set ThisIP=null where UserID = {0}", ThisMyInfo.UserID);
            DBHelps.Command(DML);
            //判断是否已连接,如果已连接那么就关闭连接
            StopContent();
        }

        private void over_Click(object sender, EventArgs e)
        {
            var DML = string.Format("update Users set ThisIP=null where UserID = {0}", ThisMyInfo.UserID);
            DBHelps.Command(DML);
            Environment.Exit(0);
        }

        private void 清空回收站ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("是否确定清空回收站？\n一旦确定将无法恢复！", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
            if (result == DialogResult.OK)
            {
                var sql = string.Format("delete from FlieInfo where UserID='{0}' and Belongs='回收站'", ThisMyInfo.UserID);
                bool result1 = DBHelps.Command(sql);
                if (result1)
                {
                    MessageBox.Show("清空成功！");
                    Dump_Click(sender, e);
                }
            }
        }

        private void 彻底删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.listView1.SelectedItems.Count > 0)
            {
                string a = listView1.SelectedItems[0].Text;//获取所选择项的名字
                DialogResult result = MessageBox.Show("是否确定彻底删除" + a + "？\n一旦确定将无法恢复！", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
                if (result == DialogResult.OK)
                {
                    var sql = string.Format("delete from FlieInfo where UserID='{0}' and original_File_name='{1}' and Belongs='回收站'", ThisMyInfo.UserID,a);
                    bool result1 = DBHelps.Command(sql);
                    if (result1)
                    {
                        MessageBox.Show("删除成功！");
                        Dump_Click(sender, e);
                    }
                }
            }
        }
        private void 恢复文件ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.listView1.SelectedItems.Count > 0)
            {
                string a = listView1.SelectedItems[0].Text;//获取所选择项的名字
                string sql = string.Format("update FlieInfo set Belongs='首页' where UserID={0} and FlieName+FlieSuffix='{1}' and Belongs='回收站'", ThisMyInfo.UserID,a);
                bool result1 = DBHelps.Command(sql);
                if (result1)
                {
                    MessageBox.Show("恢复成功");
                    Dump_Click(sender,e);
                    //ListViewItem selectedItem = this.listView1.SelectedItems[0];
                    //this.listView1.Items.Remove(selectedItem);
                }
                else
                {
                    MessageBox.Show("恢复失败");
                }
            }
        }

        private void 刷新ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Dump_Click(sender, e);
        }

        private void ReName_Click(object sender, EventArgs e)
        {
            CmmandShuxing = 1;
            File_renaming_properties file_1 = new File_renaming_properties();
            file_1.ShowDialog();
        }

        private void OpenFlie_Click(object sender, EventArgs e)
        {
            CmmandShuxing = 2;
            File_renaming_properties file_1 = new File_renaming_properties();
            file_1.ShowDialog();
        }

        private void SelectBtn_Click(object sender, EventArgs e)
        {
            if (SearchText.Text != "")
            {
                this.listView1.Items.Clear();//清楚所有项,避免重复！
                string sql = string.Format("select (f.FlieName + f.FlieSuffix) 文件名,f.FlieGetTime 上传日期,cast((FlieLength/1024/1024)as decimal(20,3)) 文件大小,f.FlieSuffix 文件类型 " +
                    "from FlieInfo f,Users u where f.UserID = u.UserID and u.UserID = '{0}' and f.original_File_name like ('%{1}%');", ThisMyInfo.UserID, SearchText.Text);

                while (DBHelps.Select(sql).Read())
                {
                    //创建ListViewItem对象，并设置Text属性
                    ListViewItem item1 = new ListViewItem(DBHelps.Select(sql)["文件名"].ToString());
                    //向ListViewItem对象中依次添加子项
                    item1.SubItems.Add(DBHelps.Select(sql)["上传日期"].ToString());
                    item1.SubItems.Add(DBHelps.Select(sql)["文件大小"].ToString());
                    //向ListView控件中添加项
                    this.listView1.Items.Add(item1);
                    //设置该文件图标
                    string Suffix = (DBHelps.Select(sql)["文件类型"].ToString());
                    item1.ImageIndex = IfSuffix.IfSuffixs(Suffix);
                }
                DBHelps.Select(sql).Close();
                DBHelps.reader = null;
            }
            else
            {
                Client_Load(sender, e);
            }
        }

        private void 打开ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string sql = string.Format("select FileDownName from FlieInfo where original_File_name='{0}'", choice_term);
            while (DBHelps.Select(sql).Read())
            {
                fileNames = DBHelps.Select(sql)["FileDownName"].ToString();
            }
            DBHelps.Select(sql).Close();
            DBHelps.reader = null;


            string ar = Directory.GetCurrentDirectory() + "\\../../Changes下载文件/" + choice_term;//放置到目标
            if (File.Exists(ar))
            {
                //MessageBox.Show("文件存在");
                System.Diagnostics.Process.Start(ar); //打开此文件。
            }
            else
            {
                //MessageBox.Show("无此文件");
                //默认下载后打开
                //下载ation地址
                string remoteUri = string.Format($"http://112.74.46.59//api/downfile" + "?filename={0}", fileNames);

                //本地存储地址
                //string ar = Directory.GetCurrentDirectory() + "\\../../Changes下载文件/" + choice_term;//放置到目标
                string myStringWebResource = null;
                WebClient myWebClient = new WebClient();
                myStringWebResource = remoteUri;
                myWebClient.DownloadFile(myStringWebResource, ar);

                System.Diagnostics.Process.Start(ar); //打开此文件。
            }
        }
        private void DownloadFlie_Click(object sender, EventArgs e)
        {
            if (choice_term==null)
            {
                MessageBox.Show("请选择文件后下载！");
            }
            else
            {
                DownLoad_Click(sender,e);
            }
        }

        private void TIME_Tick(object sender, EventArgs e)
        {
            timer.Text = DateTime.Now.ToString();
        }

        private void TiamIsOver_Tick(object sender, EventArgs e)
        {
            this.Opacity -= 0.01;
            if (this.Opacity <= 0)
            {
                TiamIsOver.Stop();
                this.Close();
            }
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {

        }

        public Action DownloadAction;
        private void 下载ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DownloadAction = Download.RightClickDownLoad;//使用Action委托执行下载方法
            DownloadAction.BeginInvoke(null,null);//开启异步执行
        }

        private void Dump_Click(object sender, EventArgs e)
        {
            PrivacyLogin.Visible = false;//隐藏隐私控件登陆容器
            PrivacyPwd.Visible = false;//隐藏隐私控件注册容器
            listView1.ContextMenuStrip = contextMenuStrip1;//重新设置右键出来的方式

            listView1.Items.Clear();

            SqlDataReader reader = DBHelps.Select(string.Format("select (FlieName + FlieSuffix)文件名,FlieGetTime 删除日期,cast((FlieLength/1024/1024)as decimal(20,3)) 文件大小,FlieSuffix 文件类型 from FlieInfo where Belongs='回收站' and UserID = {0}", ThisMyInfo.UserID));
            while (reader.Read())
            {
                ListViewItem item1 = new ListViewItem(DBHelps.reader["文件名"].ToString());

                //向ListViewItem对象中依次添加子项
                item1.SubItems.Add(DBHelps.reader["删除日期"].ToString());
                item1.SubItems.Add(DBHelps.reader["文件大小"].ToString());

                //向ListView控件中添加项
                this.listView1.Items.Add(item1);

                //设置该文件图标
                string Suffix = (DBHelps.reader["文件类型"].ToString());
                item1.ImageIndex = IfSuffix.IfSuffixs(Suffix);
            }
            reader.Close();
            DBHelps.reader = null;
        }
        public void Simi()
        {
            this.listView1.Items.Clear();//清楚所有项,避免重复！

            string sql = string.Format("select (f.FlieName + f.FlieSuffix) 文件名,f.FlieGetTime 上传日期,cast((FlieLength/1024/1024)as decimal(20,3)) 文件大小,f.FlieSuffix 文件类型 " +
                "from FlieInfo f,Users u where f.UserID = u.UserID and u.UserID = '{0}' and f.Belongs = '私密空间';", ThisMyInfo.UserID);

            while (DBHelps.Select(sql).Read())
            {
                //创建ListViewItem对象，并设置Text属性
                ListViewItem item1 = new ListViewItem(DBHelps.Select(sql)["文件名"].ToString());

                //向ListViewItem对象中依次添加子项
                item1.SubItems.Add(DBHelps.Select(sql)["上传日期"].ToString());
                item1.SubItems.Add(DBHelps.Select(sql)["文件大小"].ToString());

                //向ListView控件中添加项
                this.listView1.Items.Add(item1);

                //设置该文件图标
                string Suffix = (DBHelps.Select(sql)["文件类型"].ToString());
                item1.ImageIndex = IfSuffix.IfSuffixs(Suffix);
            }
            DBHelps.Select(sql).Close();
            DBHelps.reader = null;
        }
        private void Privacy_Click(object sender, EventArgs e)//私密空间
        {
            string sel = string.Format("select * from Users where PriPwd is not null and UserID={0}", ThisMyInfo.UserID);
            SqlDataReader reader = DBHelps.Select(sel);
            if (reader.Read())//如果有密码，则提示输入
            {
                reader.Close();
                DBHelps.reader = null;
                listView1.Items.Clear();//清空

                if (RememberLoginPrivacy)
                {
                    PrivacyLogin.Visible = false;//隐藏隐私控件登陆容器
                    listView1.ContextMenuStrip = contextMenuStrip2;//重新设置右键出来的方式
                                                                   //使用listView 显示该用户的文件-------------
                    Simi();
                }
                else
                {
                    PrivacyLogin.Visible = true;
                }
            }
            else//如果没有密码，则提示注册
            {
                listView1.Items.Clear();//清空
                PrivacyLogin.Visible = false;
                PrivacyPwd.Visible = true;
            }
            reader.Close();
            DBHelps.reader = null;


        }

        private void 移动至私密空间ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string sel = string.Format("select * from Users where PriPwd is not null and UserID={0}", ThisMyInfo.UserID);
            SqlDataReader reader = DBHelps.Select(sel);
            if (reader.Read())
            {
                reader.Close();
                DBHelps.reader = null;
                try
                {
                    if (this.listView1.SelectedItems.Count > 0)
                    {
                        string a = listView1.SelectedItems[0].Text;//获取需要隐藏的文件名

                        string sql = string.Format("update FlieInfo set Belongs='私密空间' where UserID={0} and FlieName+FlieSuffix='{1}'", ThisMyInfo.UserID,a);

                        bool result1 = DBHelps.Command(sql);
                        if (result1)
                        {
                            MessageBox.Show("移动成功！\n该文件已移动至私密空间。");
                            button3_Click(sender, e);
                        }
                    }
                }
                catch (Exception)
                {
                    MessageBox.Show("移动失败");
                }
            }
            else
            {
                MessageBox.Show("你还没开通私密空间哦(￣▽￣)");
                Privacy_Click(sender, e);
            }
            
        }

        private static bool RememberLoginPrivacy = false;
        private void PrivacyLoginButton_Click(object sender, EventArgs e)//私密空间
        {
            if (prsswordtxt.Text != "")//测试阶段先不创建密码
            {
                string sql = string.Format("select * from Users where PriPwd='{0}' and UserID={1}",prsswordtxt.Text,ThisMyInfo.UserID);
                SqlDataReader reader = DBHelps.Select(sql);
                if (reader.Read())
                {
                    reader.Close();
                    DBHelps.reader = null;
                    RememberLoginPrivacy = true;//当我登录成功，记住本次操作，下次就不用进行登录
                    Privacy_Click(sender, e);//刷新隐私空间
                }
                else
                {
                    reader.Close();
                    DBHelps.reader = null;
                    MessageBox.Show("输入有误,请重新输入！");
                }
            }

            //if (RememberLoginPrivacy)
            //{
            //    Privacy_Click(sender, e);//刷新隐私空间
            //}

            
        }

        private void button8_Click_1(object sender, EventArgs e)
        {
            SelectTheBackground background = new SelectTheBackground();
            background.Show();
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)//私密空间  打开
        {
            string sql = string.Format("select FileDownName from FlieInfo where original_File_name='{0}'", choice_term);
            while (DBHelps.Select(sql).Read())
            {
                fileNames = DBHelps.Select(sql)["FileDownName"].ToString();
            }
            DBHelps.Select(sql).Close();
            DBHelps.reader = null;


            string ar = Directory.GetCurrentDirectory() + "\\../../Changes下载文件/" + choice_term;//放置到目标
            if (File.Exists(ar))
            {
                //MessageBox.Show("文件存在");
                System.Diagnostics.Process.Start(ar); //打开此文件。
            }
            else
            {
                //MessageBox.Show("无此文件");
                //默认下载后打开
                //下载ation地址
                string remoteUri = string.Format($"http://112.74.46.59//api/downfile" + "?filename={0}", fileNames);

                //本地存储地址
                //string ar = Directory.GetCurrentDirectory() + "\\../../Changes下载文件/" + choice_term;//放置到目标
                string myStringWebResource = null;
                WebClient myWebClient = new WebClient();
                myStringWebResource = remoteUri;
                myWebClient.DownloadFile(myStringWebResource, ar);

                System.Diagnostics.Process.Start(ar); //打开此文件。
            }
        }

        private void toolStripMenuItem2_Click(object sender, EventArgs e)//私密空间  上传
        {
            UpLoadFlie_Click(sender, e);
        }

        private void toolStripMenuItem3_Click(object sender, EventArgs e)//私密空间  下载
        {
            Download.RightClickDownLoad();//调用下载类的右键下载
        }

        private void toolStripMenuItem4_Click(object sender, EventArgs e)//另存为
        {
            Download.SavedAs();
        }

        private void toolStripMenuItem5_Click(object sender, EventArgs e)//私密空间  删除
        {
            try
            {
                //右键菜单的删除功能
                DialogResult result = MessageBox.Show("确定要删除文件吗？", "", MessageBoxButtons.YesNo);
                if (result == DialogResult.Yes)
                {
                    if (this.listView1.SelectedItems.Count > 0)
                    {
                        string a = listView1.SelectedItems[0].Text;//获取删除的文件名

                        string sql = string.Format("update FlieInfo set Belongs='回收站' where UserID={0} and FlieName+FlieSuffix='{1}'", ThisMyInfo.UserID,a);

                        bool result1 = DBHelps.Command(sql);
                        if (result1)
                        {
                            MessageBox.Show("删除成功！\n已经放入回收站了。");
                            Privacy_Click(sender, e);
                        }
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show("删除失败");
            }
        }

        private void toolStripMenuItem6_Click(object sender, EventArgs e)//私密空间  刷新
        {
            Simi();
        }

        private void toolStripMenuItem7_Click(object sender, EventArgs e)//私密空间  移动首页
        {
            try
            {
                if (this.listView1.SelectedItems.Count > 0)
                {
                    string a = listView1.SelectedItems[0].Text;//获取需要隐藏的文件名

                    string sql = string.Format("update FlieInfo set Belongs='首页' where UserID={0} and FlieName+FlieSuffix='{1}'", ThisMyInfo.UserID,a);

                    bool result1 = DBHelps.Command(sql);
                    if (result1)
                    {
                        MessageBox.Show("移动成功！\n该文件已移动至首页空间。");
                        ListViewItem selectedItem = this.listView1.SelectedItems[0];
                        this.listView1.Items.Remove(selectedItem);
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show("移动失败");
            }
        }

        private void toolStripMenuItem8_Click(object sender, EventArgs e)//私密空间  重命名
        {
            ReName_Click(sender, e);
        }

        private void toolStripMenuItem9_Click(object sender, EventArgs e)//私密空间  文件属性
        {
            OpenFlie_Click(sender,e);
        }


        bool totheend = true;
        private void button9_Click(object sender, EventArgs e)//测试会员
        {
            if (totheend)
            {
                string sqlstr = string.Format("update Users set VIP=1 where UserID={0}", ThisMyInfo.UserID);
                DBHelps.Command(sqlstr);
                MessageBox.Show("切换为会员");
            }
            else
            {
                string sqlstr = string.Format("update Users set VIP=0 where UserID={0}", ThisMyInfo.UserID);
                DBHelps.Command(sqlstr);
                MessageBox.Show("切换为普通用户");
            }
            totheend = !totheend;
        }

        private void PwdButton_Click(object sender, EventArgs e)
        {
            try
            {
                string pwd = PwdText.Text;
                string pwd2 = PwdText2.Text;
                if (pwd != "" && pwd2 != "")
                {
                    if (pwd == pwd2)
                    {
                        string sql = string.Format("update Users set PriPwd='{0}' where UserID={1}", ReplaceSQLChar.ReplaceSQL(pwd2), ThisMyInfo.UserID);
                        bool result = DBHelps.Command(sql);
                        if (result)
                        {
                            MessageBox.Show("您的私密密码已经设置完毕了！\n请好好记住哦！");
                            PrivacyPwd.Visible = false;
                            PrivacyLogin.Visible = true;
                        }
                        else
                        {
                            MessageBox.Show("设置失败！");
                        }
                    }
                    else
                    {
                        MessageBox.Show("输入的信息不一致！", "提示");
                    }
                }
                else
                {
                    MessageBox.Show("请把信息填写完整！", "提示");
                }
            }
            catch (Exception q)
            {
                MessageBox.Show(q.Message);
            }
        }

        private void Directory4_Click(object sender, EventArgs e)
        {
            RememberLoginPrivacy = false;//返回登陆界面 重新登陆后点击私密空间时需要重新输入私密
            var DML = string.Format("update Users set ThisIP=null where UserID = {0}", ThisMyInfo.UserID);
            DBHelps.Command(DML);
            Hide();
            LoginHome loginHome = new LoginHome();
            loginHome.ShowDialog();
            this.Close();
        }

        private void Directory3_Click(object sender, EventArgs e)
        {
            Style.SwitchFunction(Switchfunction = 2);
        }



        //--聊天转移------------------------------------------------------------------------------------------------------------
        public Socket clientsocket { get; set; }
        public void ReceiveDate(object socket)
        {
            var proxSocket = socket as Socket;
            byte[] data = new byte[1024 * 1024];
            while (true)
            {
                int len = 0;
                try
                {
                    len = proxSocket.Receive(data, 0, data.Length, SocketFlags.None);
                }
                catch (Exception ex)
                {
                    //异常退出
                    AppendTextTolog(string.Format("服务器端：{0}非常退出", proxSocket.RemoteEndPoint.ToString()));

                    StopContent();//关闭连接

                    return;//让方法结束,终结当前客户端数据的异步线程
                }
                if (len <= 0)
                {
                    //客户端正常退出
                    AppendTextTolog(string.Format("服务器端：{0}正常退出", proxSocket.RemoteEndPoint.ToString()));
                    StopContent();//停止连接

                    return;//让方法结束,终结当前客户端数据的异步线程
                }
                //把接收到的数据放到文本框上去
                string str = Encoding.Default.GetString(data, 0, len);
                AppendTextTolog(str);
                AppendTextTolog(string.Format("接收到客户端：{0}的信息是：{1}", proxSocket.RemoteEndPoint.ToString(), str));
            }
        }
        private void StopContent()
        {
            try
            {
                //System.NullReferenceException:“未将对象引用设置到对象的实例。”
                if (clientsocket.Connected)
                {
                    clientsocket.Shutdown(SocketShutdown.Both);
                    clientsocket.Close(100);
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
            }
        }
        public void AppendTextTolog(string tex)
        {
            //Action<string> sdel = a =>{ };

            //sdel = new Action<string>(a => { });

            ////sdel+=
            //sdel("sss");
            //sdel.Invoke("sss");
            //sdel.BeginInvoke("sss", null, null);


            if (texlog.InvokeRequired)
            {
                texlog.BeginInvoke(new Action<string>(s =>
                {
                    this.texlog.Text = string.Format("{0}\r\n{1}", s, texlog.Text);
                }), tex);
                //同步方法。
                //texlog.Invoke(new Action<string>(s =>
                //{
                //    this.texlog.Text = string.Format("{0}\r\n{1}",s,texlog.Text);
                //}), tex);
            }
            else
            {
                this.texlog.Text = string.Format("{0}\r\n{1}", tex, texlog.Text);
            }
            //this.texlog.Text = string.Format("{0}\r\n{1}", tex, texlog.Text);
        }

        public static Button friend = null;

        public static string MyFriendsName = null;

        string[] button = new string[10];
        private void Friend_Click(object sender, EventArgs e)
        {
            string send = sender.ToString();
            string username = send.Substring(35);
            bool resu = false;
            for (int i = 0; i < button.Length; i++)
            {
                if (button[i] == username)
                {
                    var DML = string.Format("select ThisIP from Users where UserName='{0}'", button[i]);
                    SqlDataReader reader = DBHelps.Select(DML);
                    if (reader.Read())
                    {
                        if (reader["ThisIP"].ToString() == "")
                        {
                            FriendsState.Text = (button[i] + "(不在线)");
                        }
                        else
                        {
                            texIP.Text = reader["ThisIP"].ToString();
                            butstart_Click(sender, e);
                            FriendsState.Text = (button[i] + "(在线)");
                            resu = true;
                        }
                    }
                    reader.Close();
                    DBHelps.reader = null;
                    if (resu)
                    {
                        var DML2 = string.Format("select UserID from Users where UserName='{0}'", button[i]);
                        SqlDataReader reader2 = DBHelps.Select(DML2);
                        if (reader2.Read())
                        {
                            MyFriendsName = reader2["UserID"].ToString();
                        }
                        reader2.Close();
                        DBHelps.reader = null;
                    }
                    break;
                }
            }
        }//单击好友时绑定的公告事件
        private void AddFriends_Click_1(object sender, EventArgs e)
        {
            AddMyFriends myFriends = new AddMyFriends();
            myFriends.ShowDialog();
        }//添加好友

        private void ShareFlie_Click(object sender, EventArgs e)
        {
            int Pass = FriendsState.Text.IndexOf("不在线");
            if (Pass != -1)
            {
                MessageBox.Show("用户不在线,无法分享文件！");
            }
            else
            {
                ShareFile shareFile = new ShareFile(MyFriendsName);
                shareFile.Show();
            }
        }//分享文件
        private void butstart_Click(object sender, EventArgs e)
        {
            //客户端连接服务器端
            //1创建Socket对象
            Socket socket = new Socket
                (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);


            clientsocket = socket;

            //2连接服务器
            try
            {
                socket.Connect(IPAddress.Parse(texIP.Text), int.Parse(textport.Text));
            }
            catch (Exception ex)
            {
                MessageBox.Show("连接失败，重新连接！");
                //Thread.Sleep(500);
                //butstart_Click(this, e);
                //MessageBox.Show(ex.ToString());
                return;
            }
            //3发送消息，接收消息
            Thread thread = new Thread(new ParameterizedThreadStart(ReceiveDate));
            thread.IsBackground = true;
            thread.Start(clientsocket);
        }//开始链接
        public void butsendMsg_Click(object sender, EventArgs e)
        {
            int Pass = FriendsState.Text.IndexOf("不在线");

            if (FriendsState.Text == "未建立会话")
            {
                MessageBox.Show("请先建立会话!");
            }
            else if (Pass != -1)
            {
                MessageBox.Show("对方不在线，无法发起会话！");
            }
            else if (clientsocket.Connected)
            {
                if (texMsg.Text != "")
                {
                    byte[] data = Encoding.Default.GetBytes(texMsg.Text);
                    clientsocket.Send(data, 0, data.Length, SocketFlags.None);
                    texlog.Text += (texMsg.Text + "   ：Me" + "\r\n\r\n");
                    texMsg.Text = "";
                }
                else
                {
                    MessageBox.Show("发送的信息不能为空！");
                }

            }
        }//发送消息


        public static int Switchfunction = 0;
        private void Directory1_Click(object sender, EventArgs e)
        {
            Style.SwitchFunction(Switchfunction = 0);
            Client_Load(sender, e);
        }

        public static int RefreshListindex = 0;
        public void CurrentlyEnd_Click(object sender, EventArgs e)
        {
            //----传输完成
            SelectTheBackground.Clickstyle(RefreshListindex = 2);
            LoadListView.LoadQueue("select SaveName 文件名,OperationState 状态,cast((FileSize/1024/1024)as decimal(20,3)) 文件大小,FileSuffix 文件类型 from FlieTeamLog where OperationState= '下载完成' or OperationState = '上传完成'");
        }

        public void CurrentlyUpload_Click(object sender, EventArgs e)
        {
            //----正在上传和等待上传
            SelectTheBackground.Clickstyle(RefreshListindex = 1);
            LoadListView.LoadQueue("select SaveName 文件名,OperationState 状态,cast((FileSize/1024/1024)as decimal(20,3)) 文件大小,FileSuffix 文件类型 from FlieTeamLog where OperationState= '等待上传' or OperationState = '正在上传'");
        }

        public void CurrentlyDownload_Click(object sender, EventArgs e)
        {
            //----正在下载和等待下载
            SelectTheBackground.Clickstyle(RefreshListindex = 0);
            LoadListView.LoadQueue("select SaveName 文件名,OperationState 状态,cast((FileSize/1024/1024)as decimal(20,3)) 文件大小,FileSuffix 文件类型 from FlieTeamLog where OperationState= '等待下载' or OperationState = '正在下载'");
            //cast((FileSize/1024/1024)as decimal(20,3)) 文件大小
        }





        private void Directory2_Click(object sender, EventArgs e)
        {
            Style.SwitchFunction(Switchfunction = 1);
        }

        private void 时间排序ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PrivacyLogin.Visible = false;//隐藏隐私控件登陆容器
            listView1.ContextMenuStrip = RightClick;//重新设置右键出来的方式 
            //使用listView 显示该用户的文件-------------
            this.listView1.Items.Clear();//清楚所有项,避免重复！

            string sql = string.Format("select (f.FlieName + f.FlieSuffix) 文件名,f.FlieGetTime 上传日期,cast((FlieLength/1024/1024)as decimal(20,3)) 文件大小,f.FlieSuffix 文件类型 " +
                "from FlieInfo f,Users u where f.UserID = u.UserID and u.UserID = '{0}' and f.Belongs = '首页' order by 上传日期", ThisMyInfo.UserID);

            while (DBHelps.Select(sql).Read())
            {
                //创建ListViewItem对象，并设置Text属性
                ListViewItem item1 = new ListViewItem(DBHelps.Select(sql)["文件名"].ToString());

                //向ListViewItem对象中依次添加子项
                item1.SubItems.Add(DBHelps.Select(sql)["上传日期"].ToString());
                item1.SubItems.Add(DBHelps.Select(sql)["文件大小"].ToString());

                //向ListView控件中添加项
                this.listView1.Items.Add(item1);

                //设置该文件图标
                string Suffix = (DBHelps.Select(sql)["文件类型"].ToString());
                item1.ImageIndex = IfSuffix.IfSuffixs(Suffix);

                //item1.SubItems.

            }
            DBHelps.Select(sql).Close();
            DBHelps.reader = null;
        }

        private void 名称排序ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PrivacyLogin.Visible = false;//隐藏隐私控件登陆容器
            listView1.ContextMenuStrip = RightClick;//重新设置右键出来的方式 
            //使用listView 显示该用户的文件-------------
            this.listView1.Items.Clear();//清楚所有项,避免重复！

            string sql = string.Format("select (f.FlieName + f.FlieSuffix) 文件名,f.FlieGetTime 上传日期,cast((FlieLength/1024/1024)as decimal(20,3)) 文件大小,f.FlieSuffix 文件类型 " +
                "from FlieInfo f,Users u where f.UserID = u.UserID and u.UserID = '{0}' and f.Belongs = '首页' order by 文件名", ThisMyInfo.UserID);

            while (DBHelps.Select(sql).Read())
            {
                //创建ListViewItem对象，并设置Text属性
                ListViewItem item1 = new ListViewItem(DBHelps.Select(sql)["文件名"].ToString());

                //向ListViewItem对象中依次添加子项
                item1.SubItems.Add(DBHelps.Select(sql)["上传日期"].ToString());
                item1.SubItems.Add(DBHelps.Select(sql)["文件大小"].ToString());

                //向ListView控件中添加项
                this.listView1.Items.Add(item1);

                //设置该文件图标
                string Suffix = (DBHelps.Select(sql)["文件类型"].ToString());
                item1.ImageIndex = IfSuffix.IfSuffixs(Suffix);

                //item1.SubItems.

            }
            DBHelps.Select(sql).Close();
            DBHelps.reader = null;
        }

        private void 文件类型排序ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            button3_Click(sender, e);
        }

        private void qingkong_Click(object sender, EventArgs e)
        {
            string a = "delete FlieTeamLog";
            DBHelps.Command(a);
        }
    }
}
